package com.lxl.workbench.controller;

import com.alibaba.fastjson.JSON;
import com.lxl.commons.contants.BaseServlet;
import com.lxl.commons.contants.Contants;
import com.lxl.commons.domain.ReturnObject;
import com.lxl.commons.utils.Md5;
import com.lxl.commons.utils.UUIDUtils;
import com.lxl.settings.entity.User;
import com.lxl.settings.service.UserService;
import com.lxl.settings.service.impl.UserServiceImpl;
import com.lxl.workbench.entity.Curator;
import com.lxl.workbench.entity.Library;
import com.lxl.workbench.service.LibraryService;
import com.lxl.workbench.service.StaffService;
import com.lxl.workbench.service.impl.LibraryServiceImpl;
import com.lxl.workbench.service.impl.StaffServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 北上寻海
 */
@WebServlet({"/queryLibrary","/selectLibrary","/addLibrary","/updateLibrary","/deleteLibrary"})
public class LibraryServlet extends BaseServlet {
    /**
     * 需要用到的对象
     *  1、操作library表的libraryService
     *  2、操作user表的userService
     *  3、操作员工表的staffService
     *  4、用于前端页面数据返回的returnObject
     */
    LibraryService libraryService = new LibraryServiceImpl();
    UserService userService = new UserServiceImpl();
    StaffService staffService = new StaffServiceImpl();
    ReturnObject returnObject = new ReturnObject();

    /**
     * 根据条件查询图书馆 名称和地址
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void queryLibraryByCondition (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String libraryName = request.getParameter("libraryName");
        String libraryLocation = request.getParameter("libraryLocation");
        try {
            List<Library> libraryList = libraryService.queryLibraryByCondition(libraryName,libraryLocation);
            if(libraryList != null&&!libraryList.isEmpty()){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("查询成功");
                returnObject.setRetData(libraryList);

            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("查无该图书馆");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }
        //将数据转化为json形式传回去
        String json =  JSON.toJSONString(returnObject);
        response.getWriter().write(json);

    }


    /**
     * 通过id查要修改的图书馆的数据
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void selectLibraryConditionById (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String pageId = request.getParameter("id");
        String id = pageId.replace("/","");
        //查询数据填写到更改的div，要查三个表的数据，user，curator，library
        try {
            List<Library> libraryList  = libraryService.queryLibraryById(id);
            if(libraryList!=null&&!libraryList.isEmpty()){
                 //图书馆信息
                 Library library = libraryList.get(0);
                 String curatorId = library.getLibraryCurator();
                 List<Curator> curatorList = staffService.selectCuratorById(curatorId);
                if(curatorList!=null&&!curatorList.isEmpty()) {
                    //馆长信息
                    Curator curator = curatorList.get(0);
                    String userId = curator.getUserId();
                    List<User> userList = userService.selectUserById(userId);
                    if(userList!=null&&!userList.isEmpty()) {
                        //馆长信息
                        User user = userList.get(0);
                        //将三个对象放进list集合传去前端
                        List<Object> beanList = new ArrayList<>();
                        beanList.add(library);
                        beanList.add(curator);
                        beanList.add(user);
                        returnObject.setRetData(beanList);
                        returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                        returnObject.setMessage("查询成功");
                    }else {
                        returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                        returnObject.setMessage("查询失败");
                    }
                }else {
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("查询失败");
                }

            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("查询失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("查询失败");
        }
        String json =  JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }

    /**
     *添加图书馆，将图书馆对象封装好添加
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void addLibraryByCondition (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String userId = UUIDUtils.getUuid();
        //收集user的参数，创建对象
        User user = new User(userId,
                request.getParameter("userAccount"),
                Md5.md5(request.getParameter("password")));
        //收集curator参数，创建对象
        String curatorId = UUIDUtils.getUuid();
        Curator curator = new Curator(curatorId,
                request.getParameter("curatorName"),
                request.getParameter("gender"),
                request.getParameter("phone"),
                request.getParameter("email"),
                userId,
                Contants.CURATOR_PERMISSIONS);
        //收集library参数，创建对象
        Library library = new Library(UUIDUtils.getUuid(),
                request.getParameter("libraryName"),
                request.getParameter("libraryLocation"),
                curatorId);
        try {
            libraryService.insertLibraryByCondition(user,curator,library);
            library.setLibraryCurator(curator.getCuratorName());
            //不抛异常，成功
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("添加成功");
            returnObject.setRetData(library);
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("添加失败");
        }
       //写给前端
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }


    /**
     *更新图书馆，将图书馆对象作为条件封装好
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void updateLibraryByCondition (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //把前台数据封装好,library
        Library library = new Library();
        library.setId(request.getParameter("libraryId"));
        library.setLibraryName(request.getParameter("libraryName"));
        library.setLibraryLocation(request.getParameter("libraryLocation"));
        //curator
        Curator curator = new Curator();
        curator.setId(request.getParameter("curatorId"));
        curator.setCuratorName(request.getParameter("curatorName"));
        curator.setGender(request.getParameter("gender"));
        curator.setPhone(request.getParameter("phone"));
        curator.setEmail(request.getParameter("email"));
        //user
        User user = new User();
        user.setId(request.getParameter("userId"));
        user.setUsername(request.getParameter("username"));
        user.setPassword(Md5.md5(request.getParameter("password")));

        try {
             libraryService.updateLibraryByCondition(library,curator,user);
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("更新成功");

        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        String json =  JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }

    /**
     * 删除图书馆，根据选中的id批量删除
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void deleteLibraryConditionByIds (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String ids = request.getParameter("ids");
        String replaceId = ids.replace("/","");
        String [] libraryIds =  replaceId.split(",");
        try {
            List<Library> libraryList = libraryService.selectLibraryByIds(libraryIds);
            if(libraryList.size()>0){
                String [] curatorIds = new String[libraryList.size()];
                for(int i = 0; i < libraryList.size();i++){
                    curatorIds[i] = libraryList.get(i).getLibraryCurator();
                }
                //用curator的id去查user的id，直接查curator的表就好
                List<Curator> curatorList = staffService.selectCuratorByIds(curatorIds);
                if(curatorList.size()>0){
                    String [] userIds = new String[curatorList.size()];
                    for (int i = 0; i < curatorList.size();i++){
                        userIds[i] = curatorList.get(i).getUserId();
                    }
                    //现在三个id的数组都拿到了，删除
                    libraryService.deleteLibraryConditionByIds(libraryIds,curatorIds,userIds);
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    returnObject.setMessage("删除成功");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }

        String json =  JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }
}
